package com.ltmonitor.thread;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder.Case;

import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.ltmonitor.dao.IBaseIbatisDao;
import com.ltmonitor.entity.TerminalCommand;
import com.ltmonitor.service.ITerminalCommandService;
import com.ltmonitor.service.IUpdateDriverCardInfoService;
import com.ltmonitor.service.JT808Constants;
import com.ltmonitor.util.DateUtil;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.util.SpringApplicationContextHolder;



@Controller("BtdTimeThread")
public class BtdTimeThread extends Thread {

	private boolean threadFlg = true;//定义线程标记为true
	
	//定义更新插拔卡附件信息对象
	private IUpdateDriverCardInfoService updateCardService = null;
	//定义数据库操作服务对象
	private IBaseIbatisDao baseIbatisDao = null;
	// 定义终端命令服务对象
	private ITerminalCommandService terminalCommandService = null;
	
	private boolean channel1SendFlg = false;//定义通道1下发标记，如果已经下发则为true，未下发则为false
	private boolean channel2SendFlg = false;//同上
	private boolean channel3SendFlg = false;//同上
	private Date channelSendTime = new Date();//保存通道下发命令时间，用于延迟发送，同一车辆命令下发时间需要间隔1分钟以上
	private int sendDiffTime = 70;//定义两个通道命令发送的间隔时间，默认为70秒
	
	
	
	//设置获取线程类
	
		public boolean isThreadFlg() {
			return threadFlg;
		}

		public void setThreadFlg(boolean threadFlg) {
			this.threadFlg = threadFlg;
		}
		
	//进行数据初始化
	private void init() {
		initUpdatCardService();
		initIBaseIbatisDao();
		initITerminlCmdService();
	}
	
	private void initITerminlCmdService() {
		if(terminalCommandService == null) {
			terminalCommandService = SpringApplicationContextHolder.getBean("terminalCommandService");
		}
	}
	
	private void initIBaseIbatisDao() {
		if(baseIbatisDao == null) {
			baseIbatisDao = SpringApplicationContextHolder.getBean("baseIbatisDao");
		}
	}
	//初始化插拔卡更新服务对象
	private void initUpdatCardService() {
		if(updateCardService == null) {
			updateCardService = SpringApplicationContextHolder.getBean("updateDriverCardInfoService");
		}
	}
		
	
	public void run() {
		// TODO Auto-generated method stub
		int num = 0;
		int timer1 = 60 *3;//定义第一个时间，5分钟，更新短时插拔卡记录 60*5
		int timer2 = 60 * 60;//定义第二个时间，1小时，更新长时插拔卡记录 60*60
		init();
		while (threadFlg){ //非阻塞过程中通过判断中断标志来退出
            try {
            	
            	num ++;
//            	System.out.println("+++++++++++++++++++++");
//            	System.out.println("+++++++++++++++++++++");
//            	System.out.println("第" + num + "次线程执行");
            	
            	if(num % timer1 == 0) {
            		updateDriverCardPicInfo(1);//更新短时插拔卡信息            		
//            		System.out.println("+++++++++++++++++++++");
//                	System.out.println("+++++++++++++++++++++");
//                	System.out.println("+++++++++++++++++++++");
//                	System.out.println("更新短时插拔卡信息");
            	}
            	
            	if(num % timer2 == 0) {
            		updateDriverCardPicInfo(2);//更新长时插拔卡信息
//            		System.out.println("+++++++++++++++++++++");
//                	System.out.println("+++++++++++++++++++++");
//                	System.out.println("+++++++++++++++++++++");
//                	System.out.println("更新长时插拔卡信息");
            	}
            	
//            	sendCmd();//发送指令
            
            	
            	Thread.sleep(1000);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				
			}
        }
	}
	
	
	//更新插拔卡信息
	private void updateDriverCardPicInfo(int updateFlg) {
		if (updateCardService == null) {
			initUpdatCardService();
			
		}
		System.out.println("+++++++++++++++++++++");
    	System.out.println("+++++++++++++++++++++");
		System.out.println("开始时间 : "+new Date().toString());
		System.out.println(updateCardService);
		
		if(updateCardService != null) {
			if(updateFlg == 1) {
				JsonMessage result = updateCardService.updatePicInfo(1,3000);				
			}else if(updateFlg ==2) {
				JsonMessage result = updateCardService.updatePicInfo(24*3,8000);	
			}
//			String msg = result.isSuccess() + " , ";
//			if(result.getMessage() != null) {
//				msg += result.getMessage() + " , ";
//			}
//			if(result.getData() != null) {
//				msg += result.getData();
//			}
//			System.out.println(msg);
		}else {
//			System.out.println("更新系统对象为空......");
		}
		
//		System.out.println("结束时间 : "+new Date().toString());
		
	}
	
	
	//下发车辆数据
	/**
	 * 下发车辆牌照命令
	 * 1.判断是否为发送时间，如果是，则开始发送指定的通道命令
	 */
	private void sendCmd() {
		Date dateTemp = new Date();
		
//		System.out.println("+++++++++++++++++++++");
//		System.out.println("+++++++++++++++++++++");
//		System.out.println("校验时间   :  " + DateUtil.datetimeToString(dateTemp) );
//		String timeStr =dateTemp.getHours() + " , " + dateTemp.getMinutes() + " , " +  dateTemp.getSeconds() ;
//		System.out.println(timeStr);
//		System.out.println("channel1Flg = "  + channel1SendFlg);
//		System.out.println("channel2Flg = "  + channel2SendFlg);
//		System.out.println("channel3Flg = "  + channel3SendFlg);
//		System.out.println("channelSendtime = " + DateUtil.datetimeToString(channelSendTime));
		
		
		
		if(isSendTime(dateTemp, 4)) {
//			System.out.println("目前在发送时间..........");
			if(isSendTime(dateTemp, 1)) {
				//开始发送1通道命令
//				System.out.println("开始发送1通道命令.......................");
				channel1SendFlg = true;
				channelSendTime = new Date();//修改发送时间
				sendPicCmd(1);
//				System.out.println("发送完成.......................");
				
			}
			
			if(isSendTime(dateTemp, 2)) {
				//开始发送1通道命令
//				System.out.println("开始发送2通道命令.......................");
				channel2SendFlg = true;
				channelSendTime = new Date();//修改发送时间
				sendPicCmd(2);
//				System.out.println("发送完成.......................");
				
			}
			
			if(isSendTime(dateTemp, 3)) {
				//开始发送1通道命令
//				System.out.println("开始发送3通道命令.......................");
				channel3SendFlg = true;
				channelSendTime = new Date();//修改发送时间
				sendPicCmd(3);
//				System.out.println("发送完成.......................");
				
			}
			
			
			
		}else {//设置发送标记为false，为下次发送做准备
//			System.out.println("目前不在发送时间，初始化信息");
			if(channel1SendFlg) {
				channel1SendFlg = false;
			}
			if(channel2SendFlg) {
				channel2SendFlg = false;
			}
			if(channel3SendFlg) {
				channel3SendFlg = false;
			}
		}
		
		
		
	}
	
	//判断是否为发送时间
	private boolean isSendTime(Date dateTemp,int channelId) {
		boolean  flg = false;
		try {
			if(dateTemp.getHours() > 1 && dateTemp.getHours() < 5) { //如果时间在2点到5点之间，则不是下发命令时间
				System.out.println("+++++++++++++++++++++");
				System.out.println("+++++++++++++++++++++");
				System.out.println("2点到5点之间不发送");
				return flg;
			}
			int minutes = dateTemp.getMinutes();
			switch(channelId) {
			case 1://1通道命令时间
				if(minutes >=0 && minutes <2) {
					flg = isSendFlg(channelId);
				}else {
					flg = false;
				}
				break;
			case 2://2通道命令时间
				if(minutes >=2 && minutes <4) {
					flg = isSendFlg(channelId);
				}else {
					flg = false;
				}
				break;
			case 3://3通道命令时间
				if(minutes >=4 && minutes <6) {
					flg = isSendFlg(channelId);
				}else {
					flg = false;
				}
				break;
			case 4://判断是否为发送命令时间,分钟数大于等于6即为不发送
				if(minutes >=6) {
					flg = false;
				}else {
					flg = true;
				}
				break;
			default:
				return false;
			}
			
			//返回结果
			return flg;
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
	}
	
	//判断是否可以发送通道命令
	private boolean isSendFlg(int channelId) {
		boolean flg = false;
		try {
			switch(channelId) {
			case 1:
				return !channel1SendFlg;
			case 2:
				if(!channel2SendFlg && com.ltmonitor.web.util.DateUtil.getDiffValue(channelSendTime, new Date()) > sendDiffTime) {
					return true;
				}else {
					return false;
				}
			case 3:
				if(!channel3SendFlg && com.ltmonitor.web.util.DateUtil.getDiffValue(channelSendTime, new Date()) > sendDiffTime) {
					return true;
				}else {
					return false;
				}
				default:
			return false;
			}
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		
	}



	/**发送指定通道的拍照指令
	 * @param channedId 通道号
	 */
	private void sendPicCmd(int channedId) {
		try {
//			System.out.println("发送开始时间 : " + new Date());
			
			String queryId = "vehicle.selectAllCmdVehicles";
			List vehicleList = null;
			if(baseIbatisDao != null) {
				vehicleList = baseIbatisDao.query(queryId, null);
			}
			if(vehicleList != null && vehicleList.size() > 0) {
				String cmdData = channedId + ";1;10;0;3;5;125;125;125;125";
				//开始插入拍照命令
				for(Object obj:vehicleList) {
					Map vehMap = (Map) obj;
//					System.out.println(vehMap.get("plateNo") + " , " + vehMap.get("vehicleId") + " , " + vehMap.get("simNo")  + " ,  " + cmdData);
					TerminalCommand tc = new TerminalCommand();
					tc.setCmdType(JT808Constants.CMD_TAKE_PHOTO);
					tc.setCmdData(cmdData);
					tc.setVehicleId(Long.parseLong(vehMap.get("vehicleId").toString()));
					tc.setPlateNo(vehMap.get("plateNo").toString());
					tc.setSimNo(vehMap.get("simNo").toString());
					tc.setUserId(1);
					tc.setOwner("系统管理员");
					tc.setUpdateDate(tc.getCreateDate());
					tc.setStatus(TerminalCommand.STATUS_NEW);
					this.terminalCommandService.save(tc);
				}		
				
			}
			
//			System.out.println("发送结束时间 : " + new Date());
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	
}
